import { PokerHand } from "./PokerHand.js";
import { StraightThirdPokerHand } from "./StraightThirdPokerHand.js";
import { PokerCard } from "../PokerCard.js";
export type { PokerCard, PokerType } from "../PokerCard.js";

/** 三顺带对子 */
export class PlaneWithPairPokerHand extends PokerHand {
  public value: number;
  constructor(cards: PokerCard[]) {
    super(cards);

    /** 临时对象 */
    const tmp: any = {};
    cards.forEach((card) => {
      if (tmp[card.value]) {
        tmp[card.value] += 1;
      } else {
        tmp[card.value] = 1;
      }
    });

    this.value = Math.max(
      ...Object.keys(tmp)
        // 三张牌
        .filter((key) => tmp[key] === 3)
        // 转数字
        .map((v) => Number(v))
    );
  }

  /**
   * 判断是否飞机带翅膀(对子)：三顺＋同数量的对子。
   * @param cards 手牌
   * @returns
   */
  public static isStandard(cards: PokerCard[]) {
    const len = cards.length;

    // 少于10张牌
    if (len < 10 || len % 5 !== 0) {
      return false;
    }
    // 如果属于三顺的则排除
    if (StraightThirdPokerHand.isStandard(cards)) {
      return false;
    }

    /** 临时对象 */
    const tmp: any = {};
    cards.forEach((card) => {
      if (tmp[card.value]) {
        tmp[card.value] += 1;
      } else {
        tmp[card.value] = 1;
      }
    });

    const tmpVals = Object.values(tmp) as number[];
    // 有单张的，则不对
    if (tmpVals.includes(1)) {
      return false;
    }
    // 3的数量不准确
    if (tmpVals.filter((v) => v === 3).length !== len / 5) {
      return false;
    }

    /** 三张牌的数值 */
    const nums = Object.keys(tmp)
      // 三张牌
      .filter((key) => tmp[key] === 3)
      // 转数字
      .map((v) => Number(v))
      // 排序，从小到大
      .sort((a, b) => a - b);

    /** 如果有222，则错误 */
    if (nums.includes(13)) {
      return false;
    }

    return nums[nums.length - 1] - nums[0] + 1 === len / 5;
  }
  public isStandard = PlaneWithPairPokerHand.isStandard;
  public isBetter(target: PokerHand): boolean {
    if (target instanceof PlaneWithPairPokerHand && target.cards.length === this.cards.length) {
      return this.value > target.value;
    }

    return false;
  }
}

export default PlaneWithPairPokerHand;
